import 'package:flutter/foundation.dart';
import 'package:pwd_keeper/common/sqlite/util.dart';

class PwdKeeperManager with ChangeNotifier {
  static PwdKeeperManager instance = PwdKeeperManager();
  final sqliteUtil = SqliteUtil();
  List allPwdKeeper = [];

  String getUniqueId() {
    return DateTime.now().millisecondsSinceEpoch.toString();
  }

  void init() async {
    sqliteUtil.createDb(1);
    refresh();
  }

  Future queryAllKeeper() async {
    return query("select * from PwdKeeper");
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM PwdKeeper");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  void insert({
    String name = "",
    String account = "",
    String password = "",
    String desc = "",
    String link = "",
    String icon = "default",
  }) async {
    String id = getUniqueId();
    await sqliteUtil.insert(
        'INSERT INTO PwdKeeper(id,name,account,password,desc,link,icon) VALUES("$id","$name","$account","$password","$desc","$link","$icon")');
    refresh();
  }

  void update({
    String id = "",
    String name = "",
    String account = "",
    String password = "",
    String desc = "",
    String link = "",
    String icon = "default",
  }) async {
    await sqliteUtil.update(
      'UPDATE PwdKeeper SET name = ?, account = ?, password = ?, desc = ?, link = ?, icon = ? WHERE id = $id',
      [name, account, password, desc, link, icon],
    );
    refresh();
  }

  void delete({String id = ""}) async {
    await sqliteUtil.delete('DELETE FROM PwdKeeper WHERE id = "$id"');
    refresh();
  }

  refresh() {
    queryAllKeeper().then((res) {
      allPwdKeeper = res;
      notifyListeners();
    });
  }
}
